package org.liaohailong.library.widget.interact.audio

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.media.audiofx.Visualizer
import android.util.AttributeSet
import android.view.View
import androidx.annotation.ColorInt
import java.lang.Exception

/**
 * Author: liaohailong
 * Date: 2019/3/12
 * Time: 3:19 PM
 * Description: 音频轨迹动画
 **/
class AudioWaveView(context: Context, attributeSet: AttributeSet?, defStyle: Int) : View(context, attributeSet, defStyle) {
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
    constructor(context: Context) : this(context, null)

    private val maxCount = 32
    private var bytes: ByteArray = ByteArray(maxCount)
    private val paint = Paint()

    private var visualizer: Visualizer? = null
    fun init(audioSession: Int) {
        visualizer = Visualizer(audioSession).apply {
            setDataCaptureListener(object : Visualizer.OnDataCaptureListener {
                //采集快速傅里叶变换有关的数据
                override fun onFftDataCapture(visualizer: Visualizer?, fft: ByteArray?, samplingRate: Int) {

                }

                //采集波形数据
                override fun onWaveFormDataCapture(visualizer: Visualizer?, waveform: ByteArray?, samplingRate: Int) {
                    updateByte(waveform)
                }

            }, Visualizer.getMaxCaptureRate() / 2, true, false)
            enabled = true
        }

        paint.style = Paint.Style.FILL_AND_STROKE
        paint.color = Color.parseColor("#4DFFFFFF")//30%白色
    }

    fun release() {
        visualizer?.apply {
            try {
                release()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    private fun updateByte(waveform: ByteArray?) {
        waveform?.apply {
            val span = size / maxCount
            var pos = 0
            for (i in 0 until maxCount) {
                bytes[i] = this[pos]
                pos += span
            }
            invalidate()
        }
    }

    private fun updateColor(@ColorInt color: Int) {
        paint.color = color
        invalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        if (canvas == null || bytes.isEmpty()) return
        val itemWidth = width / (bytes.size * 2)
        //绘制宽柱状图
        for (i in 0..bytes.size - 2) {
            val left = width * i / (bytes.size - 1)
            val top = height - (bytes[i + 1] + 128).toByte() * height / 64
            val right = left + itemWidth
            val bottom = height
            canvas.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), paint)
        }
    }
}